package com.zhf.utils;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/23 21:07
 */

import java.sql.*;

/**
 * JDBC工具类
 */
public class JDBCUtils {

    //将连接信息定义为字符串常量
    public static final String DRIVERNAME=  "com.mysql.jdbc.Driver";
    public static final String URL="jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
    public static final String USER="root";
    public static final String PASSWORD="12345";

    //静态代码块
    static {
        try {
            //注册驱动
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接的静态方法
    public static Connection getConnection(){
        //获取连接对象并返回
        try {
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //关闭资源的方法
    public static void close(Connection connection, Statement statement){
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
